﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;

namespace IntraVision.Web
{
    public class Filter<TEntity> : IFilter
        where TEntity: class,new()
    {
        public List<IFilterCondition> Conditions
        {
            get;
            set;
        }

        public Filter()
        {
            Conditions = new List<IFilterCondition>();
        }

        /// <summary>
        /// Инициализация фильтра
        /// </summary>
        public void Init(NameValueCollection state)
        {
            foreach (var fc in Conditions)
                fc.Init(state);
        }

        public IQueryable<TEntity> ApplyFilter(IQueryable<TEntity> query)
        {
            if (Conditions != null)
            {
                foreach (IFilterCondition<TEntity> condition in Conditions)
                    query = condition.Filter(query);
            }
            return query;
        }

        public string Serialize(params string[] excludedColumns)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var condition in Conditions.Where(c => !excludedColumns.Contains(c.Column)))
            {
                string conditionStr = condition.ToString();
                if (!string.IsNullOrEmpty(conditionStr)) sb.Append(conditionStr).Append("&");
            }
            return sb.ToString();
        }
    }
}
